package com.suxin.http;

import com.suxin.http.model.Header;
import com.suxin.http.model.HttpRestResult;
import com.suxin.http.model.Query;
import com.suxin.http.model.RequestHttpEntity;
import com.suxin.http.request.HttpClientRequest;
import com.suxin.http.response.HttpClientResponse;
import com.suxin.http.response.handler.ResponseHandler;
import org.springframework.http.HttpMethod;
import org.springframework.web.util.UriComponentsBuilder;

import java.lang.reflect.Type;
import java.net.URI;

/**
 * @author Tang
 * @classname HttpRestTemplate
 * @description [  ]
 * @date 2023/3/2 22:54
 */
public class HttpRestTemplate extends AbstractRestTemplate {

    private final HttpClientRequest httpClientRequest;

    public HttpRestTemplate(HttpClientRequest httpClientRequest) {
        this.httpClientRequest = httpClientRequest;
    }

    /**
     * get
     * @param url
     * @param header
     * @param query
     * @param responseType
     * @param <T>
     * @return
     * @throws Exception
     */
    public <T> HttpRestResult<T> get(String url, Header header, Query query, Type responseType) throws Exception {
        return execute(url, HttpMethod.GET.name(), new RequestHttpEntity(header, query), responseType);
    }

    /**
     * post
     * @param url
     * @param header
     * @param query
     * @param body
     * @param responseType
     * @param <T>
     * @return
     * @throws Exception
     */
    public <T> HttpRestResult<T> post(String url, Header header, Query query,Object body, Type responseType) throws Exception {
        return execute(url, HttpMethod.POST.name(), new RequestHttpEntity(header, query,body), responseType);
    }

    /**
     * 真正执行请求的
     * @param url
     * @param method
     * @param requestHttpEntity
     * @param responseType
     * @param <T>
     * @return
     * @throws Exception
     */
    private <T> HttpRestResult<T> execute(String url, String method, RequestHttpEntity requestHttpEntity, Type responseType) throws Exception{
        // 构建请求的uri
        final URI uri = UriComponentsBuilder
                .fromHttpUrl(url)
                .query(requestHttpEntity.getQuery().toQueryUrl())
                .build()
                .toUri();
        // 选择 一个 ResponseHandler
        final ResponseHandler responseHandler = super.selectResponseHandler(responseType);
        //  发起请求
        HttpClientResponse response = requestHttpClient().execute(uri,method,requestHttpEntity);
        // 响应处理
        return responseHandler.handlerResponse(response);
    }

    public HttpClientRequest requestHttpClient() {
        return httpClientRequest;
    }
}